package com.bw.mvp.http;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 双重校验锁：会写锁代码 + 会解释
 */
public class RetrofitManager {
    private static volatile RetrofitManager instance;
    private RetrofitManager(){}
    public static RetrofitManager getInstance(){
        //第一次判断:避免每个线程都直接判断锁是否被占用，减少锁的占用，减少性能的开销
        //线程 1 2 3
        if(instance == null){
            //线程1 2 3
            synchronized (RetrofitManager.class){
                //第二次判断：保证只创建一次对象
                if(instance == null){
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }
    private Retrofit mRetrofit;
    public Retrofit getRetrofit(){
        if(mRetrofit == null){
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl("http://10.161.9.80:8886/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create()) //使用工厂模式创建转换器
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //工厂模式：Call对象---->Observable对象
                    .build();
        }
        return mRetrofit;
    }



}
